package com.robotserver.orders.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.robotserver.orders.common.DateFormatUtil;
import com.robotserver.orders.common.DateUtil;
import com.robotserver.orders.common.Math;
import com.robotserver.orders.common.Tools;
import com.robotserver.orders.entity.AlimmTokens;
import com.robotserver.orders.entity.TbOrders;
import com.robotserver.orders.enums.BizStatus;
import com.robotserver.orders.mapper.AlimmTokensMapper;
import com.robotserver.orders.mapper.TbOrdersMapper;
import com.robotserver.orders.service.TbSettleOrderSyncService;
import com.robotserver.orders.vo.TbkOrderTimeVO;
import com.taobao.api.ApiException;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkScOrderDetailsGetRequest;
import com.taobao.api.response.TbkScOrderDetailsGetResponse;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Auther: jianghan
 * @Date: 2019/11/8 11:16
 * @Description:
 */
@Service
public class TbSettleOrderSyncServiceImpl implements TbSettleOrderSyncService {

    private static Logger logger = LoggerFactory.getLogger(TbSettleOrderSyncServiceImpl.class);

    @Autowired
    private TbOrdersMapper tbOrdersMapper;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private AlimmTokensMapper alimmTokensMapper;

    private static long pagesize = 100;
    private static long querytype = 3; // 结算时间
    private static long tkstatus = 3;  // 状态为结算订单
    private static long jumptype = 1;  // 向前翻页

    @Override
    public void syncAlimmUnitOrder(List<TbkOrderTimeVO> tbkOrderTimeVOList, AlimmTokens alimmTokens, TaobaoClient client,Long orderScene) {
        for (TbkOrderTimeVO tbkOrderTimeVO:tbkOrderTimeVOList){
            syncTimeUnitOrder(tbkOrderTimeVO,alimmTokens,client,null,1l,orderScene);
//            try {
//                Thread.sleep(20); //线程停止20毫秒
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        }
    }

    @Override
    public void syncTimeUnitOrder(TbkOrderTimeVO tbkOrderTime, AlimmTokens alimmTokens, TaobaoClient client,String positionindex,Long pageNo,Long orderScene) {
        try {
            TbkScOrderDetailsGetRequest req = new TbkScOrderDetailsGetRequest();
            //logger.info("-------------"+alimmTokens.getAccessToken()+"::"+alimmTokens.getUserName()+"::"+tbkOrderTime.getBeginTime()+"::"+tbkOrderTime.getEndTime()+"::"+positionindex+"::"+pageNo);
            req.setQueryType(querytype);
            if (StringUtils.isNotBlank(positionindex)){
                req.setPositionIndex(positionindex);
            }
            req.setPageSize(pagesize);
            req.setTkStatus(tkstatus);
            req.setStartTime(tbkOrderTime.getBeginTime());
            req.setEndTime(tbkOrderTime.getEndTime());
            req.setJumpType(jumptype);
            req.setPageNo(pageNo);
            req.setOrderScene(orderScene);

            TbkScOrderDetailsGetResponse rsp = client.execute(req, alimmTokens.getAccessToken());

            // 处理入库
            if (rsp.getData()!=null){
                ordersAdd(rsp.getData().getResults(),alimmTokens);
                if (rsp.getData().getHasNext()){
                    pageNo = pageNo+1;
                    syncTimeUnitOrder(tbkOrderTime,alimmTokens,client,rsp.getData().getPositionIndex(),pageNo, orderScene);
                }else{
                    // 修改心跳
                    if (alimmTokens.getId()!=null){
                        int now = DateUtil.getNowTime();
                        alimmTokensMapper.updateSettleHeartbeat(alimmTokens.getId(),now);
                    }
                }
            }else {
                // 修改心跳
                if (alimmTokens.getId()!=null){
                    int now = DateUtil.getNowTime();
                    alimmTokensMapper.updateSettleHeartbeat(alimmTokens.getId(),now);
                }
            }
        } catch (Exception e) {
            logger.error("sync tb settlement order err:{}",e.getMessage());
        }
    }

    @Transactional
    @Override
    public void ordersAdd(List<TbkScOrderDetailsGetResponse.PublisherOrderDto> orders,AlimmTokens alimmTokens) {
        int now = DateUtil.getNowTime();
        if (orders==null || orders.size()==0){
            return ;
        }
        for (TbkScOrderDetailsGetResponse.PublisherOrderDto order:orders){
            Date modifyTimeDate = DateFormatUtil.StringToDateFormat(order.getModifiedTime(),"yyyy-MM-dd HH:mm:ss");
            Integer modifyTime = DateUtil.getTime(modifyTimeDate);
            //支付总金额
            int alipayTotalPrice = Math.currencyFormatToF(order.getAlipayTotalPrice());
            // 查询订单是否存在
            TbOrders tbOrder = tbOrdersMapper.getByOrderNo(order.getTradeParentId(),order.getTradeId());
            if (tbOrder!=null){
                if (tbOrder.getTkStatus().intValue() == order.getTkStatus().intValue()
                    && Tools.getInteger(tbOrder.getModifiedTime()).intValue() == Tools.getInteger(modifyTime).intValue()
                        && Tools.getInteger(tbOrder.getAlipayTotalPrice()).intValue() == alipayTotalPrice){
                    continue;
                }else {
                    logger.info("update tb settlement order:parentId: {},childId: {},tkstatus:{}",new Object[]{order.getTradeParentId(),order.getTradeId(),order.getTkStatus()});
                    // 修改
                    tbOrder.setUpdateTime(now);
                    tbOrder.setAdzoneId(order.getAdzoneId());
                    tbOrder.setAdzoneName(order.getAdzoneName());
                    tbOrder.setAlimamaRate(Math.strToDouble(order.getAlimamaRate()));
                    tbOrder.setAlimamaShareFee(Math.currencyFormatToF(order.getAlimamaShareFee()));
                    tbOrder.setAlimmUserId(String.valueOf(alimmTokens.getUserId()));
                    tbOrder.setAlimmUserName(alimmTokens.getUserName());
                    tbOrder.setAlipayTotalPrice(Math.currencyFormatToF(order.getAlipayTotalPrice()));
                    tbOrder.setAppKey(order.getAppKey());

                    //modify by 2021-03-10 18:00 by liuqi
                    tbOrder.setAlscId(order.getAlscId());
                    tbOrder.setAlscPid(order.getAlscPid());
                    tbOrder.setLxRid(order.getLxRid());
                    tbOrder.setIsLx(order.getIsLx());
                    tbOrder.setMarketingType(order.getMarketingType());
                    tbOrder.setModifiedTime(modifyTime);

                    tbOrder.setBizStatus(BizStatus.settlement.getValue());
                    tbOrder.setClickTime(DateUtil.getStrTime(order.getClickTime()));
                    tbOrder.setDepositPrice(Math.currencyFormatToF(order.getDepositPrice()));
                    tbOrder.setFlowSource(order.getFlowSource());
                    tbOrder.setIncomeRate(Math.strToDouble(order.getIncomeRate()));
                    tbOrder.setItemCategoryName(order.getItemCategoryName());
                    tbOrder.setItemId(order.getItemId());
                    tbOrder.setItemImg(order.getItemImg());
                    tbOrder.setItemLink(order.getItemLink());
                    tbOrder.setItemNum(order.getItemNum());
                    tbOrder.setItemPrice(Math.currencyFormatToF(order.getItemPrice()));
                    tbOrder.setItemTitle(order.getItemTitle());

                    tbOrder.setOrderType(order.getOrderType());
                    tbOrder.setPayPrice(Math.currencyFormatToF(order.getPayPrice()));
                    tbOrder.setPubId(order.getPubId());
                    tbOrder.setPubShareFee(Math.currencyFormatToF(order.getPubShareFee()));
                    tbOrder.setPubSharePreFee(Math.currencyFormatToF(order.getPubSharePreFee()));
                    tbOrder.setPubShareRate(Math.strToDouble(order.getPubShareRate()));
                    tbOrder.setRefundTag((int) order.getRefundTag().longValue());
                    tbOrder.setRelationId(order.getRelationId());
                    String sellerNick = order.getSellerNick();
                    if(StringUtils.isNotBlank(sellerNick)){
                        tbOrder.setSellerNick(sellerNick.length() > 32 ? sellerNick.substring(0,30): sellerNick);
                    }
                    tbOrder.setSellerShopTitle(order.getSellerShopTitle());
                    tbOrder.setSiteId(order.getSiteId());
                    tbOrder.setSiteName(order.getSiteName());

                    if (tbOrder.getSpecialId()==null && order.getSpecialId()!=null){
                        tbOrder.setSpecialId(order.getSpecialId());
                    }

                    if (tbOrder.getRelationId()==null && order.getRelationId()!=null){
                        tbOrder.setRelationId(order.getRelationId());
                    }

                    tbOrder.setSubsidyRate(Math.strToDouble(order.getSubsidyRate()));
                    tbOrder.setSubsidyFee(Math.currencyFormatToF(order.getSubsidyFee()));
                    tbOrder.setSubsidyType(order.getSubsidyType());
                    tbOrder.setTbDepositTime(DateUtil.getStrTime(order.getTbDepositTime()));
                    tbOrder.setTbPaidTime(DateUtil.getStrTime(order.getTbPaidTime()));
                    tbOrder.setTerminalType(order.getTerminalType());
                    tbOrder.setTkCommissionFeeForMediaPlatform(Math.currencyFormatToF(order.getTkCommissionFeeForMediaPlatform()));
                    tbOrder.setTkCommissionPreFeeForMediaPlatform(Math.currencyFormatToF(order.getTkCommissionPreFeeForMediaPlatform()));
                    tbOrder.setTkCommissionRateForMediaPlatform(Math.strToDouble(order.getTkCommissionRateForMediaPlatform()));
                    tbOrder.setTkCreateTime(DateUtil.getStrTime(order.getTkCreateTime()));
                    tbOrder.setTkEarningTime(DateUtil.getStrTime(order.getTkEarningTime()));
                    tbOrder.setTkOrderRole(order.getTkOrderRole());
                    tbOrder.setTkPaidTime(DateUtil.getStrTime(order.getTkPaidTime()));
                    tbOrder.setTradeId(order.getTradeId());
                    tbOrder.setTradeParentId(order.getTradeParentId());
                    tbOrder.setTkTotalRate(Math.strToDouble(order.getTkTotalRate()));
                    tbOrder.setTkStatus((int)order.getTkStatus().longValue());
                    tbOrder.setTotalCommissionRate(Math.strToDouble(order.getTotalCommissionRate()));
                    tbOrder.setTotalCommissionFee(Math.currencyFormatToF(order.getTotalCommissionFee()));
                    tbOrder.setTkDepositTime(DateUtil.getStrTime(order.getTkDepositTime()));
                    tbOrder.setPid("mm_"+order.getPubId()+"_"+order.getSiteId()+"_"+order.getAdzoneId());
                    tbOrdersMapper.update(tbOrder);
                }
            }else{
                // 添加
                logger.info("add tb settlement order:parentId: {},childId: {},tkstatus:{}",new Object[]{order.getTradeParentId(),order.getTradeId(),order.getTkStatus()});
                TbOrders newOrder = new TbOrders();
                newOrder.setId(IdWorker.getId());
                newOrder.setCreateTime(now);
                newOrder.setUpdateTime(now);
                newOrder.setAdzoneId(order.getAdzoneId());
                newOrder.setAdzoneName(order.getAdzoneName());
                newOrder.setAlimamaRate(Math.strToDouble(order.getAlimamaRate()));
                newOrder.setAlimamaShareFee(Math.currencyFormatToF(order.getAlimamaShareFee()));
                newOrder.setAlimmUserId(String.valueOf(alimmTokens.getUserId()));
                newOrder.setAlimmUserName(alimmTokens.getUserName());
                newOrder.setAlipayTotalPrice(Math.currencyFormatToF(order.getAlipayTotalPrice()));
                newOrder.setAppKey(order.getAppKey());

                //modify by 2021-03-10 18:00 by liuqi
                newOrder.setAlscId(order.getAlscId());
                newOrder.setAlscPid(order.getAlscPid());
                newOrder.setLxRid(order.getLxRid());
                newOrder.setIsLx(order.getIsLx());
                newOrder.setMarketingType(order.getMarketingType());
                newOrder.setModifiedTime(modifyTime);

                newOrder.setBizStatus(BizStatus.settlement.getValue());
                newOrder.setClickTime(DateUtil.getStrTime(order.getClickTime()));
                newOrder.setDepositPrice(Math.currencyFormatToF(order.getDepositPrice()));
                newOrder.setFlowSource(order.getFlowSource());
                newOrder.setIncomeRate(Math.strToDouble(order.getIncomeRate()));
                newOrder.setItemCategoryName(order.getItemCategoryName());
                newOrder.setItemId(order.getItemId());
                newOrder.setItemImg(order.getItemImg());
                newOrder.setItemLink(order.getItemLink());
                newOrder.setItemNum(order.getItemNum());
                newOrder.setItemPrice(Math.currencyFormatToF(order.getItemPrice()));
                newOrder.setItemTitle(order.getItemTitle());

                newOrder.setOrderType(order.getOrderType());
                newOrder.setPayPrice(Math.currencyFormatToF(order.getPayPrice()));
                newOrder.setPubId(order.getPubId());
                newOrder.setPubShareFee(Math.currencyFormatToF(order.getPubShareFee()));
                newOrder.setPubSharePreFee(Math.currencyFormatToF(order.getPubSharePreFee()));
                newOrder.setPubShareRate(Math.strToDouble(order.getPubShareRate()));
                newOrder.setRefundTag((int) order.getRefundTag().longValue());
                newOrder.setRelationId(order.getRelationId());
                String sellerNick = order.getSellerNick();
                if(StringUtils.isNotBlank(sellerNick)){
                    newOrder.setSellerNick(sellerNick.length() > 32 ? sellerNick.substring(0,30): sellerNick);
                }
                newOrder.setSellerShopTitle(order.getSellerShopTitle());
                newOrder.setSiteId(order.getSiteId());
                newOrder.setSiteName(order.getSiteName());
                newOrder.setSpecialId(order.getSpecialId());
                newOrder.setSubsidyRate(Math.strToDouble(order.getSubsidyRate()));
                newOrder.setSubsidyFee(Math.currencyFormatToF(order.getSubsidyFee()));
                newOrder.setSubsidyType(order.getSubsidyType());
                newOrder.setTbDepositTime(DateUtil.getStrTime(order.getTbDepositTime()));
                newOrder.setTbPaidTime(DateUtil.getStrTime(order.getTbPaidTime()));
                newOrder.setTerminalType(order.getTerminalType());
                newOrder.setTkCommissionFeeForMediaPlatform(Math.currencyFormatToF(order.getTkCommissionFeeForMediaPlatform()));
                newOrder.setTkCommissionPreFeeForMediaPlatform(Math.currencyFormatToF(order.getTkCommissionPreFeeForMediaPlatform()));
                newOrder.setTkCommissionRateForMediaPlatform(Math.strToDouble(order.getTkCommissionRateForMediaPlatform()));
                newOrder.setTkCreateTime(DateUtil.getStrTime(order.getTkCreateTime()));
                newOrder.setTkEarningTime(DateUtil.getStrTime(order.getTkEarningTime()));
                newOrder.setTkOrderRole(order.getTkOrderRole());
                newOrder.setTkPaidTime(DateUtil.getStrTime(order.getTkPaidTime()));
                newOrder.setTradeId(order.getTradeId());
                newOrder.setTradeParentId(order.getTradeParentId());
                newOrder.setTkTotalRate(Math.strToDouble(order.getTkTotalRate()));
                newOrder.setTkStatus((int)order.getTkStatus().longValue());
                newOrder.setTotalCommissionRate(Math.strToDouble(order.getTotalCommissionRate()));
                newOrder.setTotalCommissionFee(Math.currencyFormatToF(order.getTotalCommissionFee()));
                newOrder.setTkDepositTime(DateUtil.getStrTime(order.getTkDepositTime()));
                newOrder.setPid("mm_"+order.getPubId()+"_"+order.getSiteId()+"_"+order.getAdzoneId());
                tbOrdersMapper.add(newOrder);
            }
        }
    }

    @Async("taskExecutor")
    @Override
    public void threadSyncOrder(List<TbkOrderTimeVO> tbkOrderTimeVOList, List<AlimmTokens> alimmTokens, TaobaoClient client,  String lockName,Long orderScene) {
        threadLockSyncOrder(tbkOrderTimeVOList,alimmTokens,client,lockName,orderScene);
    }

    @Override
    public void threadLockSyncOrder(List<TbkOrderTimeVO> tbkOrderTimeVOList, List<AlimmTokens> alimmTokens, TaobaoClient client,  String lockName,Long orderScene) {

        if (alimmTokens.size()>0){
            AlimmTokens token = null;
            RLock lock = null;
            try {
                lock = redissonClient.getLock(lockName);
                lock.lock();
                token = alimmTokens.get(0);
                // 删除对象
                alimmTokens.remove(token);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (lock!=null){
                    lock.unlock();
                }
            }
            if (token!=null){
                logger.info(lockName+"::token>"+token.getUserId());
                syncAlimmUnitOrder(tbkOrderTimeVOList,token,client,orderScene);
                threadLockSyncOrder(tbkOrderTimeVOList,alimmTokens,client,lockName,orderScene);
            }
        }
    }

    @Async("taskExecutor")
    @Override
    public void threadSyncOrder_consumer(List<TbkOrderTimeVO> tbkOrderTimeVOList, AlimmTokens alimmTokens, TaobaoClient client, Long orderScene) {
        syncAlimmUnitOrder(tbkOrderTimeVOList,alimmTokens,client,orderScene);
    }

}
